
#ifndef __MY_BUFFER__
#define __MY_BUFFER__
// 日志缓冲区
#include "utils.hpp"
#include <vector>
#include <cassert>
namespace wzh
{
#define DEFAULT_BUFFER_SIZE (1 * 1024 * 1024)
#define THRESHOLD_BUFFER_SIZE (8 * 1024 * 1024)
#define INCREMENT_BUFFER_SIZE (1 * 1024 * 1024)
    class Buffer
    {
    public:
        Buffer() : _buffer(DEFAULT_BUFFER_SIZE), _write_idx(0), _read_idx(0) {}

        void push(const char *data, size_t len)
        {
            // if(len > writeAbleSize()) return;
            ensureEnoughSize(len);
            // 1.将数据拷贝进缓冲区
            std::copy(data, data + len, &_buffer[_write_idx]);
            // 2.将当前位置移动向后偏移
            moveWrite(len);
        }

        const char *begin()
        {
            return &_buffer[_read_idx];
        }

        size_t readAbleSize()
        {
            return (_write_idx - _read_idx);
        }

        size_t writeAbleSize()
        {
            return (_buffer.size() - _write_idx);
        }

        void moveRead(size_t len)
        {
            assert(len <= readAbleSize());
            _read_idx += len;
        }

        void reset() // 重置读写位置
        {
            _read_idx = 0;
            _write_idx = 0;
        }

        void swap(Buffer &buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(_read_idx, buffer._read_idx);
            std::swap(_write_idx, buffer._write_idx);
        }

        bool empty()
        {
            return (_read_idx == _write_idx);
        }

    private:
        void ensureEnoughSize(size_t len)
        {
            if (len <= writeAbleSize())
                return;
            size_t new_size = 0;
            if (_buffer.size() < THRESHOLD_BUFFER_SIZE)
            {
                new_size = _buffer.size() * 2 + len;
            }
            else
            {
                new_size = _buffer.size() + INCREMENT_BUFFER_SIZE + len;
            }
            _buffer.resize(new_size);
        }

        void moveWrite(size_t len)
        {
            assert(len <= _buffer.size());
            _write_idx += len;
        }

    private:
        std::vector<char> _buffer;
        size_t _read_idx;
        size_t _write_idx;
    };
}
#endif